//
//  JDMainViewController.swift
//  JDWeiBo
//
//  Created by apple on 15/6/23.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit

class JDMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        addChildViewControllers()
        
        let tab = JDMainTabBar()
        
        setValue(tab, forKeyPath: "tabBar")
        
        tab.compoesButton.addTarget(self, action: "compoesButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
    }
    
    ///  按钮监听方法
    func compoesButtonClick() {
        
//        print(__FUNCTION__)
        
    }
    
    
    ///  调用 addChildViewController 添加所有控制器
    private func addChildViewControllers() {
        
        // 取巧加载子控制器
        let path = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil)
        
        let data = NSData(contentsOfFile: path!)
        
//        print(data)
        
        do {
            let ar = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
            
            for dict in ar as! [[String : String]] {
                addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!)
            }
        } catch {
//            print(error)
            // 为了保险 沙盒，网络数据失败 可以用从本地方法加载
            addChildViewController("JDHomeTableViewController", title: "首页", imageName: "tabbar_home")
    
            addChildViewController("JDMessageTableViewController", title: "消息", imageName: "tabbar_message_center")
    
            addChildViewController("JDDiscoverTableViewController", title: "发现", imageName: "tabbar_discover")
    
            addChildViewController("JDProfileTableViewController", title: "我的", imageName: "tabbar_profile")
            
        }
    }

    
    
    ///  添加控制器抽取方法
    ///
    ///  :param: vc        子控制器
    ///  :param: title     标题
    ///  :param: imageName 图片
    private func addChildViewController(vcName: String, title: String, imageName: String) {
        
        tabBar.tintColor = UIColor.orangeColor()
        
//        print(NSBundle.mainBundle().infoDictionary)
        
        let s = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
        
        let cls: AnyClass = NSClassFromString(s + "." + vcName)!
        
        let vc = cls.new() as! UIViewController
        
        vc.title = title
        
        vc.tabBarItem.image = UIImage(named: imageName)
        
        vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted")
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }

}
